package com.tywh;

import com.tywh.pojo.EntiyTest;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.InputStreamRequestEntity;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.*;

import static com.tywh.constant.Constant.*;
import static com.tywh.utils.GetToken.GetAccesstoken;

/**
 * @ClassName TestDemo
 * @Description SOAP方式调用
 * @Author xhx
 * @Date 2019/7/29 10:57
 * @Version 1.0
 */
public class TestDemo {

    public static void main(String[] args) {

//        String appid2 = "18042802944202";
//        String appsecret2 = "3609978a-b789-6e62-042e-51015092c77d";
//        String nonce2 = "tongyuwuhan";
//        String timestamp2 = "123456";
//
//        String a = timestamp2 + appid2 + appsecret2 + nonce2;
//        a = MD5Util.MD5Encode(a, "utf8");
//        System.out.println("11111111111111:::" + a);
//
//        String b = GetAccesstoken(appid2, timestamp2, nonce2, appsecret2);
//        System.out.println("22222222222222:::" + b);

        //方法名
//            String method = METHOD;
        //请求参数
//            String appid = APPID;
//            String appsecret = APPSECRET;
//            String ifname = IFNAME;
        //随机字符串是可以随时改的
//            String nonce = NONCE;

        try {
            //sdl地址
            String wsdl = WSDL;

            String timestamp = String.valueOf(System.currentTimeMillis());

            String accesstoken = GetAccesstoken(APPID, timestamp, NONCE, APPSECRET);
            //请求数据
            List<EntiyTest> entiyTestList = new ArrayList<EntiyTest>();
            EntiyTest entiyTest = new EntiyTest("1","123","22","EE");
            entiyTestList.add(entiyTest);
            String data = com.alibaba.fastjson.JSON.toJSONString(entiyTestList);
            System.out.println("请求参数：" + data);
            //请求参数拼接到地址后
            wsdl = wsdl + "?appid=" + APPID + "&ifname=" + IFNAME + "&timestamp=" + timestamp + "&nonce=" + NONCE + "&accesstoken=" + accesstoken;
            //访问服务 返回格式一般为xml，或是json。此处返回json
            String response = accessService(wsdl, METHOD, data, "result");

            System.out.println("返回值：" + response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 访问服务
     *
     * @param wsdl   wsdl地址
     * @param method 方法名
     * @param jsonStr   参数
     * @return
     * @throws Exception
     */
    public synchronized static String accessService(String wsdl, String method, String jsonStr, String result) throws Exception {

        String soapResponseData = "";
        //拼接SOAP，此处数据模板从对方给的文档获取（如：http://192.168.88.204:8090/api/TscmService.asmx/SpdTrans）
        StringBuffer soapRequestData = new StringBuffer("");
        soapRequestData.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
        soapRequestData.append("<soap12:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap12=\"http://www.w3.org/2003/05/soap-envelope\">");
        soapRequestData.append("<soap12:Body>");
        soapRequestData.append("<" + method + ">");
        soapRequestData.append("<request>");
        soapRequestData.append(jsonStr);
        soapRequestData.append("</request>");
        soapRequestData.append("</" + method + ">");
        soapRequestData.append("</soap12:Body>" + "</soap12:Envelope>");
        PostMethod postMethod = new PostMethod(wsdl);
        // 然后把Soap请求数据添加到PostMethod中
        byte[] b = null;
        InputStream is = null;
        try {
            b = soapRequestData.toString().getBytes("utf-8");
            is = new ByteArrayInputStream(b, 0, b.length);
            //contentType应与对方文档中一致 text/xml
            RequestEntity re = new InputStreamRequestEntity(is, b.length, "text/xml; charset=UTF-8");
            postMethod.setRequestEntity(re);

            HttpClient httpClient = new org.apache.commons.httpclient.HttpClient();
            int status = httpClient.executeMethod(postMethod);

            if (status == 200) {
                System.out.println("请求成功，返回状态码：" + status);
//                System.out.println(postMethod.getResponseBodyAsString());
                  soapResponseData = postMethod.getResponseBodyAsString();
//                soapResponseData = getMesage(postMethod.getResponseBodyAsString(), result);
            }else {
                System.out.println("请求失败，返回状态码：" + status);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                is.close();
            }
        }
        return soapResponseData;
    }

    /*public static String GetAccesstoken(String appid, String timestamp, String nonce, String appsecret) {

            //拼接成数组
            String[] input = { appid.toLowerCase(),appsecret.toLowerCase(),timestamp.toLowerCase(),nonce.toLowerCase()};
            //排序（按照ascii码从小到大）
            Arrays.sort(input);

            String tmpStr = "";
            for(int i=0;i<input.length;i++){
                tmpStr = tmpStr + input[i];
            }
            System.out.println("拼接字符串：" + tmpStr);
            //MD5加密
            tmpStr = MD5Util.MD5Encode(tmpStr,"utf8");
            tmpStr = tmpStr.toLowerCase();

            System.out.println("MD5后字符串：" + tmpStr);
            return tmpStr;
        }*/

        /**
         * @Author xhx
         * @Description //TODO 如果对方返回xml，此方法解析xml文件
         * @Date 2019/7/29 11:12
         * @Param [soapAttachment, result]
         * @return java.lang.String
         **/
    public static String getMesage(String soapAttachment, String result) {
        if (result == null) {
            return null;
        }
        if (soapAttachment != null && soapAttachment.length() > 0) {
            int begin = soapAttachment.indexOf("<return>");
            begin = soapAttachment.indexOf(">", begin);
            int end = soapAttachment.indexOf("</return>");
            String str = soapAttachment.substring(begin + 1, end);
            str = str.replaceAll("<", "<");
            str = str.replaceAll(">", ">");
            return str;
        } else {
            return "";
        }
    }

}
